package com.fengze.shop.common.config;

import java.io.IOException;
import java.io.Serializable;

import com.fengze.shop.common.cache.ConfigConstant;
import lombok.extern.slf4j.Slf4j;
import org.jdom.CDATA;
import org.jdom.Element;

/**
 * 配置文件中选项--抽象类
 */
@Slf4j
public abstract class AbstractItem implements Serializable {

    private static final long serialVersionUID = 407798282558040339L;

    protected Element element = null;

    public String getDescription() {
        String desc = this.element.getChild(ConfigConstant.DESCRIPTION).getText();

        return desc == null ? "" : desc;
    }

    public void setDescription(String desc) {
        this.addElement(ConfigConstant.DESCRIPTION, desc);
    }

    public String getName() {
        return element.getChild(ConfigConstant.NAME).getText();
    }

    public void setName(String itemName) {
        this.addElement(ConfigConstant.NAME, itemName);
    }

    protected void addElement(String name, String value) {
        this.element.removeChild(name);
        Element ele = new Element(name);
        if (value.indexOf('&') != -1 || value.indexOf('<') != -1
                || value.indexOf('>') != -1) {
            CDATA cdata = new CDATA(value);
            ele.addContent(cdata);
        } else {
            ele.setText(value);
        }
        this.element.addContent(ele);
    }

    public void setElement(Element ele) {
        this.element = ele;
    }

    protected Element getElement() {
        return this.element;
    }

    public String toString() {
        String xml = "";
        try {
            java.io.StringWriter sw = new java.io.StringWriter(1000);
            org.jdom.output.XMLOutputter out = new org.jdom.output.XMLOutputter();
            out.output(this.element, sw);
            xml = sw.toString();
        } catch (IOException ex) {
            log.error("toString error: {}", ex);
        }
        return xml;
    }

}
